package cn.yusei.teamTribe.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class SmsUtil {

	private static final String SERVER_URL = "https://open.ucpaas.com/ol/sms";
	private static final String SEND_SMS_URL = SERVER_URL + "/sendsms";
	private static final String DEFAULT_ENCODING = "utf-8";
	private static final int TIME_OUT = 10000;
	
	public static String sendSms(String sid, String token, String appid, String templateid, String param, String mobile, String uid) {
		String result = "";
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("sid", sid);
			jsonObject.put("token", token);
			jsonObject.put("appid", appid);
			jsonObject.put("templateid", templateid);
			jsonObject.put("param", param);
			jsonObject.put("mobile", mobile);
			jsonObject.put("uid", uid);
			String body = jsonObject.toJSONString();
			result = SmsUtil.postJson(SEND_SMS_URL, body, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String postJson(String url, String body, String charset) {
		String result = null;
		if (null == charset) {
			charset = DEFAULT_ENCODING;
		}
		CloseableHttpClient httpClient = null;
		HttpPost httpPost = null;
		try {
			httpClient = HttpConnectionManager.getInstance().getHttpClient();
			httpPost = new HttpPost(url);
			// 设置连接超时,设置读取超时
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(TIME_OUT)	
	                .setSocketTimeout(TIME_OUT)	
	                .build();
			httpPost.setConfig(requestConfig);
			httpPost.setHeader("Accept", "application/json");
			httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
			// 设置参数
			StringEntity se = new StringEntity(body, "UTF-8");
			httpPost.setEntity(se);
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
}
